package freighttmpl

import (
	"context"
	"strconv"
	"strings"
	"time"

	"mall/common/globalkey"
	"mall/common/moneyx"
	enum "mall/service/backend/common/enum/setting"
	"mall/service/backend/common/errorx"
	"mall/service/backend/common/i18n"
	"mall/service/setting/model"
	"mall/service/setting/rpc/internal/svc"
	"mall/service/setting/rpc/internal/utils/errorhandler"
	"mall/service/setting/rpc/types/setting"

	"github.com/volatiletech/null/v8"
	"github.com/zeromicro/go-zero/core/logx"
)

type BackendUpdateFreightTemplateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewBackendUpdateFreightTemplateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BackendUpdateFreightTemplateLogic {
	return &BackendUpdateFreightTemplateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// group: freighttmpl
func (l *BackendUpdateFreightTemplateLogic) BackendUpdateFreightTemplate(in *setting.FreightTemplateInfo) (*setting.BaseResp, error) {
	if in.Id == nil || *in.Id == 0 {
		return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
	}

	id := *in.Id

	data, err := l.svcCtx.FreightTemplate.FindOneNoCache(l.ctx, nil, id)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	if in.Name != nil {
		data.Name = strings.TrimSpace(*in.Name)

		if len(data.Name) == 0 {
			logx.Errorw("udpate freight template failed, its name is required")
			return nil, errorx.NewInvalidArgumentError("setting.freightTemplateNameRequired")
		}

		filterMap := make(map[string]map[string][]any)
		filterMap[model.SysFreightTemplateColumns.Name] = map[string][]any{
			"equalTo": []any{data.Name},
		}
		list, _, err := l.svcCtx.FreightTemplate.GetList(l.ctx, model.M{
			"pageSize": uint64(2),
			"select":   ",",
		}, -1, filterMap)
		if err != nil {
			return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
		}

		count := len(list)
		if count > 1 {
			return nil, errorx.NewAlreadyExistsError("setting.freightTemplateAlreadyExists")
		}

		if count == 1 && list[0].ID != id {
			return nil, errorx.NewAlreadyExistsError("setting.freightTemplateAlreadyExists")
		}
	}
	if in.Remark != nil {
		data.Remark = strings.TrimSpace(*in.Remark)
	}
	if in.FreeShipping != nil {
		data.FreeShipping = uint8(*in.FreeShipping)
	}
	if in.ChargeMode != nil {
		data.ChargeMode = uint8(*in.ChargeMode)
	}
	if in.Sort != nil {
		data.Sort = uint16(*in.Sort)
	}
	if in.Status != nil {
		data.Status = uint8(*in.Status)
	}
	data.UpdatedAt = time.Now()
	sysFreightTemplateRel := &model.SysFreightTemplateRel{}
	if len(in.Restrictions) > 0 {
		relFilterMap := make(map[string]map[string][]any)
		relFilterMap[model.SysFreightTemplateRestrictionColumns.TemplateID] = map[string][]any{
			"equalTo": []any{id},
		}
		rel, _, err := l.svcCtx.FreightTemplate.GetRestrictionList(l.ctx, model.M{}, -1, relFilterMap)
		if err != nil {
			return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
		}

		if len(rel) > 0 { // 原有的 Restrictions（决定现有的是增还是改）
			var rids []uint64
			oridMap := make(map[uint64]struct{})
			for _, v := range rel {
				rids = append(rids, v.RestrictionID)
				oridMap[v.RestrictionID] = struct{}{}
			}

			// 现有的 Restrictions（决定原有的是删还是留）
			nridMap := make(map[uint64]struct{})
			for _, v := range in.Restrictions {
				var restriction model.SysFreightTemplateRestriction
				restriction.TemplateID = id
				if v.Regions != nil {
					restriction.Regions = null.JSONFrom([]byte(strings.TrimSpace(*v.Regions)))
				}
				if v.Mode != nil {
					restriction.Mode = uint8(*v.Mode)

					switch restriction.Mode {
					case enum.FreightTemplateRestrictionAmount:
						if v.Threshold != nil {
							if i, err := moneyx.ParseAmount(*v.Threshold); err == nil && i > 0 {
								restriction.Threshhold = uint64(i)
							} else {
								return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
							}
						}
					case enum.FreightTemplateRestrictionNumber:
						if v.Threshold != nil {
							if i, err := strconv.ParseInt(*v.Threshold, 10, 32); err == nil && i > 0 {
								restriction.Threshhold = uint64(i)
							} else {
								return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
							}
						}
					default:
						return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
					}
				}
				if v.Sort != nil {
					restriction.Sort = uint16(*v.Sort)
				}
				if v.Status != nil {
					restriction.Status = uint8(*v.Status)
				} else {
					restriction.Status = uint8(globalkey.StatusEnabled)
				}

				if v.Id != nil && *v.Id > 0 {
					if _, ok := oridMap[*v.Id]; ok { // 有值且是有效值
						nridMap[*v.Id] = struct{}{}
						restriction.RestrictionID = *v.Id
					}
				}

				sysFreightTemplateRel.Restrictions = append(sysFreightTemplateRel.Restrictions, &restriction)
			}

			for _, rid := range rids {
				if _, ok := nridMap[rid]; !ok { // 当前不存在的值
					sysFreightTemplateRel.DelRestrictionIds = append(sysFreightTemplateRel.DelRestrictionIds, rid)
				}
			}
		}
	}
	if len(in.Rules) > 0 {
		relFilterMap := make(map[string]map[string][]any)
		relFilterMap[model.SysFreightTemplateRuleColumns.TemplateID] = map[string][]any{
			"equalTo": []any{id},
		}
		rel, _, err := l.svcCtx.FreightTemplate.GetRuleList(l.ctx, model.M{}, -1, relFilterMap)
		if err != nil {
			return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
		}

		if len(rel) > 0 { // 原有的 Rules（决定现有的是增还是改）
			var rids []uint64
			oridMap := make(map[uint64]struct{})
			for _, v := range rel {
				rids = append(rids, v.RuleID)
				oridMap[v.RuleID] = struct{}{}
			}

			// 现有的 Rules（决定原有的是删还是留）
			nridMap := make(map[uint64]struct{})
			for _, v := range in.Rules {
				var rule model.SysFreightTemplateRule
				rule.TemplateID = id
				if v.Regions != nil {
					rule.Regions = null.JSONFrom([]byte(strings.TrimSpace(*v.Regions)))
				}
				if in.ChargeMode != nil {
					rule.ChargeMode = uint8(*in.ChargeMode)

					switch rule.ChargeMode {
					case enum.FreightTemplateRuleNumber:
						if v.FirstUnit != nil {
							if i, err := strconv.ParseInt(*v.FirstUnit, 10, 32); err == nil && i > 0 {
								rule.FirstUnit = uint64(i)
							} else {
								return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
							}
						}
						if v.ContinueUnit != nil {
							if i, err := strconv.ParseInt(*v.ContinueUnit, 10, 32); err == nil && i > 0 {
								rule.ContinueUnit = uint64(i)
							} else {
								return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
							}
						}
					case enum.FreightTemplateRuleWeight:
						if v.FirstUnit != nil {
							if i, err := moneyx.ParseWeight(*v.FirstUnit); err == nil && i > 0 {
								rule.FirstUnit = uint64(i)
							} else {
								return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
							}
						}
						if v.ContinueUnit != nil {
							if i, err := moneyx.ParseWeight(*v.ContinueUnit); err == nil && i > 0 {
								rule.ContinueUnit = uint64(i)
							} else {
								return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
							}
						}
					case enum.FreightTemplateRuleVolume:
						if v.FirstUnit != nil {
							if i, err := moneyx.ParseVolume(*v.FirstUnit); err == nil && i > 0 {
								rule.FirstUnit = uint64(i)
							} else {
								return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
							}
						}
						if v.ContinueUnit != nil {
							if i, err := moneyx.ParseVolume(*v.ContinueUnit); err == nil && i > 0 {
								rule.ContinueUnit = uint64(i)
							} else {
								return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
							}
						}
					default:
						return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
					}
				}
				if v.FirstPrice != nil {
					if i, err := moneyx.ParseAmount(*v.FirstPrice); err == nil && i > 0 {
						rule.FirstPrice = uint64(i)
					} else {
						return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
					}
				}
				if v.ContinuePrice != nil {
					if i, err := moneyx.ParseAmount(*v.ContinuePrice); err == nil && i > 0 {
						rule.ContinuePrice = uint64(i)
					} else {
						return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
					}
				}
				if v.Sort != nil {
					rule.Sort = uint16(*v.Sort)
				}
				if v.Status != nil {
					rule.Status = uint8(*v.Status)
				} else {
					rule.Status = uint8(globalkey.StatusEnabled)
				}

				if v.Id != nil && *v.Id > 0 {
					if _, ok := oridMap[*v.Id]; ok { // 有值且是有效值
						nridMap[*v.Id] = struct{}{}
						rule.RuleID = *v.Id
					}
				}

				sysFreightTemplateRel.Rules = append(sysFreightTemplateRel.Rules, &rule)
			}

			for _, rid := range rids {
				if _, ok := nridMap[rid]; !ok { // 当前不存在的值
					sysFreightTemplateRel.DelRuleIds = append(sysFreightTemplateRel.DelRuleIds, rid)
				}
			}
		}
	}
	err = l.svcCtx.FreightTemplate.Update(l.ctx, nil, data, sysFreightTemplateRel)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	return &setting.BaseResp{
		Msg: i18n.UpdateSuccess,
	}, nil
}
